package com.wangsh.train.web.back.controller;

import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.wangsh.train.cla.service.IClassOperService;
import com.wangsh.train.common.controller.BaseController;
import com.wangsh.train.common.pojo.ApiResponse;
import com.wangsh.train.common.pojo.ApiResponseEnum;
import com.wangsh.train.common.util.ConstatFinalUtil;
import com.wangsh.train.common.util.PageInfoUtil;
import com.wangsh.train.ques.pojo.AExamDesc;
import com.wangsh.train.ques.service.IExamDbService;
import com.wangsh.train.ques.service.IExamOperService;
import com.wangsh.train.system.pojo.ASysFile;
import com.wangsh.train.system.pojo.ASysPro;
import com.wangsh.train.system.pojo.ASysTech;
import com.wangsh.train.system.service.ISystemDbService;
import com.wangsh.train.users.pojo.AAdmins;

/**
 * 	系统后台操作
 * 	@author wangsh
 */
@Controller
@RequestMapping("/back/system/")
public class SystemBackController extends BaseController
{
	@Resource
	private ISystemDbService systemDbService;
	@Resource
	private IExamDbService examDbService;
	@Resource
	private IExamOperService examOperService;
	@Resource
	private IClassOperService classOperService;
	
	/**
	 * 添加系统设置管理提交操作
	 * 
	 * @return
	 */
	@RequestMapping(value = "/reloadSystem", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String reloadSystem()
	{
		/* 数据库操作 */
		ApiResponse<Object> apiResponse = this.systemDbService.reloadSystem();
		ConstatFinalUtil.SYS_LOGGER.info("--重新加载结果:{}--", apiResponse.toJSON().toJSONString());
		/* 统计课时 */
		Map<String,Object> condMap = new HashMap<String, Object>();
		ApiResponse<Object> operStatApiResponse = this.classOperService.operStatDataService(condMap);
		ConstatFinalUtil.SYS_LOGGER.info("--统计课时:{}--", operStatApiResponse.toJSON().toJSONString());
		return apiResponse.toJSON().toJSONString();
	}
	
	/**
	 * 系统文件列表页面
	 * @return
	 */
	@RequestMapping("/sysFileList")
	public String sysFileList(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--sysFileList--");
		/* 分页信息 */
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);
		String relaId = request.getParameter("relaId");
		String fileType = request.getParameter("fileType");
		String fileRelaType = request.getParameter("fileRelaType");
		request.setAttribute("relaId", relaId);
		request.setAttribute("fileType", fileType);
		request.setAttribute("fileRelaType", fileRelaType);
		
		/* 搜索条件,生成公共的搜索条件 */
		Map<String, Object> condMap = this.proccedSearch(request);
		condMap.put("fileType",fileType);
		condMap.put("fileRelaType", fileRelaType);
		condMap.put("relaId", relaId);
		/* 查询数据库
		 * 所有的数据以JSON的形式返回
		 *  */
		ApiResponse<ASysFile> response = this.systemDbService.findCondListSysFileService(pageInfoUtil, condMap);
		/* 将结果存储到Request中 */
		model.addAttribute("response", response.toJSON());
		return "/back/system/sysFileList";
	}
	
	/**
	 * 打开系统文件添加页面
	 * @return
	 */
	@RequestMapping("/sysFileInsert")
	public String sysFileInsert(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--sysFileInsert--");
		return "/back/system/sysFileInsert";
	}
	
	/**
	 * 打开系统文件添加页面
	 * @return
	 */
	@RequestMapping(value = "/sysFileInsertSubmit",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String sysFileInsertSubmit(HttpServletRequest request,Model model, ASysFile sysFile)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--sysFileInsertSubmit--");
		
		ApiResponse<Object> dbResponse = new ApiResponse<Object>();
		try
		{
			String pubTimeStr = request.getParameter("pubTimeStr");
			sysFile.setPubTime(this.dateFormatUtil.strDateTime(pubTimeStr));
			
			dbResponse = this.systemDbService.saveOneSysFileService(sysFile);
			/* 存储结果 */
			model.addAttribute("response", dbResponse.toJSON());
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("添加一条记录失败了",e);
			dbResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
			Map<String, String> infoMap = new HashMap<String, String>();
			/* 报错信息的占位符 */
			infoMap.put("errinfo", e.toString());
			dbResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(dbResponse.getCode() + "") , infoMap);
		}
		return dbResponse.toJSON().toJSONString();
	}
	
	/**
	 * 打开系统文件更新页面
	 * @return
	 */
	@RequestMapping("/sysFileUpdate")
	public String sysFileUpdate(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--sysFileUpdate--");
		/* 从session中获取信息 */
		String id = request.getParameter("id");
		/* 准备请求的信息 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", id);
		ApiResponse<ASysFile> apiResponse = this.systemDbService.findOneSysFileService(condMap);
		model.addAttribute("response", apiResponse.toJSON());
		
		String operType = request.getParameter("operType");
		if("update".equalsIgnoreCase(operType))
		{
			/* 根据不同的请求跳转不同的页面 */
			return "/back/system/sysFileUpdate";
		}else if("file".equalsIgnoreCase(operType))
		{
			/* 上传文件 */
			model.addAttribute("name", "系统文件上传");
			model.addAttribute("url", "/back/system/sysFileFileUpdateSubmit.htm?operType=" + operType + "&sysFileId=" + id);
			return this.uploadFile;
		}
		return "/back/system/sysFileInfo";
	}
	
	/**
	 * 打开系统文件更新页面
	 * @return
	 */
	@RequestMapping(value = "/sysFileUpdateSubmit",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String sysFileUpdateSubmit(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--sysFileUpdateSubmit--");
		ApiResponse<Object> dbResponse = new ApiResponse<Object>();
		try
		{
			/* 从session中获取信息 */
			String id = request.getParameter("id");
			/* 准备请求的信息 */
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("id", id);
			ApiResponse<ASysFile> apiResponse = this.systemDbService.findOneSysFileService(condMap);
			ASysFile sysFile = apiResponse.getDataOneJava() ; 
			model.addAttribute("response", apiResponse.toJSON());
			
			/* 接收参数 */
			String relaId = request.getParameter("relaId");
			String content = request.getParameter("content");
			
			String fileType = request.getParameter("fileType");
			String fileRelaType = request.getParameter("fileRelaType");
			String status = request.getParameter("status");
			
			sysFile.setRelaId(Integer.valueOf(relaId));
			sysFile.setContent(content);
			
			sysFile.setFileType(Byte.valueOf(fileType));
			sysFile.setFileRelaType(Byte.valueOf(fileRelaType));
			sysFile.setStatus(Byte.valueOf(status));
			
			String pubTimeStr = request.getParameter("pubTimeStr");
			sysFile.setPubTime(this.dateFormatUtil.strDateTime(pubTimeStr));
			
			/* 根据不同的请求跳转不同的页面 */
			dbResponse = this.systemDbService.updateOneSysFileService(sysFile);
			/* 存储结果 */
			model.addAttribute("response", dbResponse.toJSON());
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("更新一条记录失败了",e);
			dbResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
			Map<String, String> infoMap = new HashMap<String, String>();
			/* 报错信息的占位符 */
			infoMap.put("errinfo", e.toString());
			dbResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(dbResponse.getCode() + "") , infoMap);
		}
		return dbResponse.toJSON().toJSONString();
	}
	
	/**
	 * 打开系统文件更新页面
	 * @return
	 */
	@RequestMapping(value = "/sysFileFileUpdateSubmit",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String sysFileFileUpdateSubmit(HttpServletRequest request,Model model,MultipartFile file)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--sysFileUpdateSubmit--");
		ApiResponse<Object> dbResponse = new ApiResponse<Object>();
		try
		{
			/* 从session中获取信息 */
			String sysFileId = request.getParameter("sysFileId");
			/* 准备请求的信息 */
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("id", sysFileId);
			ApiResponse<ASysFile> apiResponse = this.systemDbService.findOneSysFileService(condMap);
			ASysFile sysFile = apiResponse.getDataOneJava() ; 
			model.addAttribute("response", apiResponse.toJSON());
			
			Map<String, Object> paramsMap = new HashMap<String,Object>();
			try
			{
				if(file != null)
				{
					ConstatFinalUtil.SYS_LOGGER.info("name:{},oriName:{}" , file.getName() , file.getOriginalFilename());
					paramsMap.put("fileName", file.getOriginalFilename());
					paramsMap.put("inputStream", file.getInputStream());
					paramsMap.put("fileSize", file.getSize());
				}
			} catch (IOException e)
			{
				ConstatFinalUtil.SYS_LOGGER.error("上传文件失败了;");
			}
			
			/* 根据不同的请求跳转不同的页面 */
			dbResponse = this.systemDbService.updateOneSysFileService(sysFile,paramsMap);
			/* 存储结果 */
			model.addAttribute("response", dbResponse.toJSON());
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("更新一条记录失败了",e);
			dbResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
			Map<String, String> infoMap = new HashMap<String, String>();
			/* 报错信息的占位符 */
			infoMap.put("errinfo", e.toString());
			dbResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(dbResponse.getCode() + "") , infoMap);
		}
		return dbResponse.toJSON().toJSONString();
	}
	
	/* ==== 系统设置管理开始 ==== */
	/**
	 * 系统设置管理页面
	 * 
	 * @return
	 */
	@RequestMapping("/sysProList")
	public String sysProList(HttpServletRequest request, Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--sysProList--");
		/* 接收参数 */
		String proType = request.getParameter("proType");
		if(proType == null)
		{
			proType = "" ; 
		}
		request.setAttribute("proType", proType);
		
		String operType = request.getParameter("operType");
		if(operType == null)
		{
			operType = "" ; 
		}
		request.setAttribute("operType", operType);
		/* 分页信息 */
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);
		/* 搜索条件,生成公共的搜索条件 */
		Map<String, Object> condMap = this.proccedSearch(request);
		condMap.put("operType", operType);
		condMap.put("proType", proType);

		/*
		 * 查询数据库 所有的数据以JSON的形式返回
		 */
		ApiResponse<ASysPro> response = this.systemDbService.findCondListSysProService(pageInfoUtil, condMap);
		/* 将结果存储到Request中 */
		model.addAttribute("response", response.toJSON());
		return "/back/system/sysProList";
	}

	/**
	 * 打开添加系统设置管理
	 * 
	 * @return
	 */
	@RequestMapping("/sysProInsert")
	public String sysProInsert()
	{
		ConstatFinalUtil.SYS_LOGGER.info("--sysProInsert--");
		return "/back/system/sysProInsert";
	}

	/**
	 * 添加系统设置管理提交操作----
	 * 
	 * @return
	 */
	@RequestMapping(value = "/sysProInsertSubmit", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String sysProInsertSubmit(String pubTimeStr, ASysPro sysPro)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--sysProInsertSubmit--");
		/* 为对象赋值 */

		sysPro.setPubTime(this.dateFormatUtil.strDateTime(pubTimeStr));// 发布时间
		/* 保存结果 */
		ApiResponse response = this.systemDbService.saveOneSysProService(sysPro);
		ConstatFinalUtil.SYS_LOGGER.info("--系统设置管理添加返回结果:{}--", response.toJSON());
		return response.toJSON().toJSONString();
	}

	/**
	 * 打开更新系统设置管理页面
	 * 
	 * @return
	 */
	@RequestMapping("/sysProUpdate")
	public String sysProUpdate(String id, String operType, Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--sysProUpdate--");
		/* 准备查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", id);
		/* 查询数据库 */
		ApiResponse<ASysPro> response = this.systemDbService.findOneSysProService(condMap);
		/* 存储request */
		model.addAttribute("response", response.toJSON());

		if ("update".equalsIgnoreCase(operType))
		{
			return "/back/system/sysProUpdate";
		}
		return "/back/system/sysProInfo";
	}

	/**
	 * 添加系统设置管理提交操作
	 * 
	 * @return
	 */
	@RequestMapping(value = "/sysProUpdateSubmit", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String sysProUpdateSubmit(String id, HttpServletRequest request, Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--SysProUpdateSubmit--");
		/* 准备查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", id);
		/* 查询数据库 */
		ApiResponse<ASysPro> response = this.systemDbService.findOneSysProService(condMap);
		/* 获取java对象 */
		ASysPro sysPro = response.getDataOneJava();

		/* 接收参数 */
		String name = request.getParameter("name");
		String engName = request.getParameter("engName");
		String content = request.getParameter("content");
		String status = request.getParameter("status");
		String operType = request.getParameter("operType");
		String proType = request.getParameter("proType");
		String vals = request.getParameter("vals");
		String pubTimeStr = request.getParameter("pubTimeStr");

		/* 设置属性 */
		sysPro.setName(name);
		sysPro.setEngName(engName);
		sysPro.setContent(content);
		sysPro.setStatus(Byte.valueOf(status));
		sysPro.setProType(Byte.valueOf(proType));
		sysPro.setOperType(Byte.valueOf(operType));
		sysPro.setVals(vals);

		sysPro.setPubTime(this.dateFormatUtil.strDateTime(pubTimeStr));
		// 更新时间不用获取
		sysPro.setUpdateTime(new Date());
		/* 数据库操作 */
		ApiResponse dbRes = systemDbService.updateOneSysProService(sysPro);

		ConstatFinalUtil.SYS_LOGGER.info("--系统设置管理添加返回结果:{}--", dbRes.toJSON());
		return dbRes.toJSON().toJSONString();
	}
	
	/**
	 * 系统技术列表页面
	 * @return
	 */
	@RequestMapping("/sysTechList")
	public String sysTechList(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--sysTechList--");
		/* 分页信息 */
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);
		String cateId = request.getParameter("cateId");
		request.setAttribute("cateId", cateId);
		
		/* 搜索条件,生成公共的搜索条件 */
		Map<String, Object> condMap = this.proccedSearch(request);
		condMap.put("cateId",cateId);
		condMap.put("extend", "true");
		/* 查询数据库
		 * 所有的数据以JSON的形式返回
		 *  */
		ApiResponse<ASysTech> response = this.systemDbService.findCondListSysTechService(pageInfoUtil, condMap);
		/* 将结果存储到Request中 */
		model.addAttribute("response", response.toJSON());
		
		/* 要做批量操作;如果存在就默认选中,不存在就删除 */
		String operType = request.getParameter("operType");
		String id = request.getParameter("id");
		if("examDesc".equalsIgnoreCase(operType))
		{
			/* 考试试卷概要 */
			condMap.clear();
			condMap.put("id", id);
			ApiResponse<AExamDesc> examApiResponse = this.examDbService.findOneExamDescService(condMap);
			request.setAttribute("selectResponse", examApiResponse.toJSON());
		}
		request.setAttribute("operType", operType);
		request.setAttribute("id", id);
		return "/back/system/sysTechList";
	}
	
	/**
	 * 打开系统技术添加页面
	 * @return
	 */
	@RequestMapping("/sysTechInsert")
	public String sysTechInsert(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--sysTechInsert--");
		return "/back/system/sysTechInsert";
	}
	
	/**
	 * 打开系统技术添加页面
	 * @return
	 */
	@RequestMapping(value = "/sysTechInsertSubmit",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String sysTechInsertSubmit(HttpServletRequest request,Model model, ASysTech sysTech)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--sysTechInsertSubmit--");
		ApiResponse<Object> dbResponse = new ApiResponse<Object>();
		
		AAdmins admins = (AAdmins) this.findObjfromSession(request, "admins");
		
		sysTech.setCreateId(admins.getId());
		
		String pubTimeStr = request.getParameter("pubTimeStr");
		sysTech.setPubTime(this.dateFormatUtil.strDateTime(pubTimeStr));
		
		dbResponse = this.systemDbService.saveOneSysTechService(sysTech);
		/* 存储结果 */
		model.addAttribute("response", dbResponse.toJSON());
		return dbResponse.toJSON().toJSONString();
	}
	
	/**
	 * 打开系统技术更新页面
	 * @return
	 */
	@RequestMapping("/sysTechUpdate")
	public String sysTechUpdate(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--sysTechUpdate--");
		/* 从session中获取信息 */
		String id = request.getParameter("id");
		/* 准备请求的信息 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", id);
		condMap.put("extend", "true");
		ApiResponse<ASysTech> apiResponse = this.systemDbService.findOneSysTechService(condMap);
		model.addAttribute("response", apiResponse.toJSON());
		
		String operType = request.getParameter("operType");
		if("update".equalsIgnoreCase(operType))
		{
			/* 根据不同的请求跳转不同的页面 */
			return "/back/system/sysTechUpdate";
		}
		return "/back/system/sysTechInfo";
	}
	
	/**
	 * 打开系统技术更新页面
	 * @return
	 */
	@RequestMapping(value = "/sysTechUpdateSubmit",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String sysTechUpdateSubmit(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--sysTechUpdateSubmit--");
		ApiResponse<Object> dbResponse = new ApiResponse<Object>();
		/* 从session中获取信息 */
		String id = request.getParameter("id");
		/* 准备请求的信息 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", id);
		ApiResponse<ASysTech> apiResponse = this.systemDbService.findOneSysTechService(condMap);
		ASysTech sysTech = apiResponse.getDataOneJava() ; 
		model.addAttribute("response", apiResponse.toJSON());
		
		/* 接收参数 */
		String cateId = request.getParameter("cateId");
		String content = request.getParameter("content");
		
		String name = request.getParameter("name");
		String website = request.getParameter("website");
		String status = request.getParameter("status");
		
		sysTech.setCateId(Integer.valueOf(cateId));
		sysTech.setName(name);
		sysTech.setContent(content);
		sysTech.setWebsite(website);
		sysTech.setStatus(Byte.valueOf(status));
		
		String pubTimeStr = request.getParameter("pubTimeStr");
		sysTech.setPubTime(this.dateFormatUtil.strDateTime(pubTimeStr));
		
		/* 根据不同的请求跳转不同的页面 */
		dbResponse = this.systemDbService.updateOneSysTechService(sysTech);
		/* 存储结果 */
		model.addAttribute("response", dbResponse.toJSON());
		return dbResponse.toJSON().toJSONString();
	}
	
	/**
	 * 技术批量操作
	 * @return
	 */
	@RequestMapping(value = "/sysTechBatch" , produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String sysTechBatch(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--sysTechBatch--");
		Map<String, Object> condMap = new HashMap<String, Object>();
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		/* 从session中获取信息 */
		String[] ids = request.getParameterValues("ids");
		
		/* 操作类型 */
		String operType = request.getParameter("operType");
		String relaId = request.getParameter("relaId");
		if(ids != null)
		{
			int totalNum = ids.length ; 
			int succedNum = 0 ; 
			int failedNum = 0 ; 
			for (int i = 0; i < ids.length; i++)
			{
				String id = ids[i];
				if("status".equalsIgnoreCase(operType))
				{
					String status = request.getParameter("status");
					
					condMap.clear();
					condMap.put("id", id);
					ApiResponse<ASysTech> apiResponseDb = this.systemDbService.findOneSysTechService(condMap);
					ASysTech sysTech = apiResponseDb.getDataOneJava();
					/* 设置状态 */
					sysTech.setStatus(Byte.valueOf(status));
					sysTech.setPubTime(new Date());
					
					ApiResponse<Object> sysTechClassResponse = this.systemDbService.updateOneSysTechService(sysTech);
					if(sysTechClassResponse.getCode() == ApiResponseEnum.STATUS_SUCCESS.getStatus())
					{
						succedNum ++ ; 
					}else
					{
						failedNum ++ ; 
					}
				}
			}
			
			/* 如果是批量操作 */
			if("examDesc".equalsIgnoreCase(operType))
			{
				/* 处理考试类型 */
				condMap.clear();
				condMap.put("techIds", ids);
				condMap.put("relaId", relaId);
				/* 返回结果 */
				apiResponse = this.examOperService.updateOneExamDescService(condMap);
				succedNum = totalNum ; 
			}
			
			StringBuffer sb = new StringBuffer();
			sb.append("总条数:" + totalNum + ";");
			sb.append("成功条数:" + succedNum + ";");
			sb.append("失败条数:" + failedNum + ";");
			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
			apiResponse.setInfo(sb.toString(), Collections.EMPTY_MAP);
		}
		return apiResponse.toJSON().toJSONString();
	}
	/*====技术表结束====*/
}
